/*
https://www.rustfinity.com/practice/rust/challenges/aor-2024-8/description
*/
use std::{fs::File, io::Write};
pub struct LogQuery<'a> {
    logs: &'a Vec<String>,
}

impl<'a> LogQuery<'a> {
    pub fn new(logs: &'a Vec<String>) -> Self {
        LogQuery { logs }
    }

    pub fn search(&self, keyword: &str) -> Vec<&'a String> {
        self.logs
            .iter()
            .filter(|log| log.contains(keyword))
            .collect()
    }

    pub fn export_to_file(&self, keyword: &str, path: &str) -> std::io::Result<()> {
        // 🎁 Your code here! 🎁
        let logs = self.search(keyword);
        let mut file = File::create(path)?;
        for log in logs {
            writeln!(file, "{}", log)?;
        }
        Ok(())
    }
}

/*
pub fn export_to_file(&self, keyword: &str, path: &str) -> std::io::Result<()> {
        let mut file = OpenOptions::new()
            .write(true)
            .append(true)
            .create(true)
            .open(path)?;
        let logs = self.search(keyword);
        for log in &logs {
            writeln!(&mut file, "{}", log)?;
        }
        Ok(())
    }
*/

/*
pub fn export_to_file(&self, keyword: &str, path: &str) -> std::io::Result<()> {
        // 🎁 Your code here! 🎁
        let logs = self.search(keyword);
        let mut file = File::create(path)?;
        for log in logs {
            match writeln!(file, "{}", log) {
                Err(e) => return Err(e),
                _ => continue,
            }
        }
        Ok(())
    }
*/

/*
pub fn export_to_file(&self, keyword: &str, path: &str) -> std::io::Result<()> {
        // 🎁 Your code here! 🎁
        let logs = self.search(keyword);
        let mut file = File::create(path)?;
        let mut writer = BufWriter::new(file);
        for res in self.search(keyword) {
            writer.write_all(res.as_bytes())?;
            writer.write(&[b'\n'])?;
        }
        Ok(())
    }
*/

/*
 pub fn export_to_file(&self, keyword: &str, path: &str) -> std::io::Result<()> {
        // 🎁 Your code here! 🎁
        let logs = self.search(keyword);
        let mut file = File::create(path)?;
        for line in logs.iter() {
            file.write_all(line.as_bytes())?;
            file.write_all("\n".as_bytes() )?;
        }
        Ok
*/
